<template>
  <div v-loading="fullscreenLoading" class="app-container">
    <el-row>
      <el-col :span="4" style="border: 1px solid #cdd0d6; text-align: center">
        <el-radio-group v-model="radioEl">
          <el-radio value="dev">测试环境</el-radio>
          <el-radio value="product">正式环境</el-radio>
        </el-radio-group>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="5" style="border: 1px solid #cdd0d6; text-align: center">
        <el-radio-group v-model="radioClient">
          <el-radio value="TIANMA">天马</el-radio>
          <el-radio value="XIAOMI">小米</el-radio>
          <el-radio value="BOE">京东方</el-radio>
        </el-radio-group>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="7">
        <el-select v-model="productSpecName" placeholder="请选择FGCODE" style="width: 100%" filterable clearable>
          <el-option v-for="item in FgcodeOptions" :key="item.productSpecName" :label="item.productSpecName" :value="item.productSpecName" />
        </el-select>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="4">
        <!-- <el-input v-model="form.boxId" style="width: 240px" @input="boxIdChange" placeholder="箱号" /> -->
        <el-input v-model="boxId" style="width: 200px" placeholder="外箱号(可粘贴Excel整列)" />
      </el-col>
    </el-row>
    <el-row style="height: 2px"> </el-row>
    <el-row>
      <el-col :span="4">
        <div class="input-with-label">
          <label class="input-label">ASN号</label>
          <el-input v-model="asnNo" style="width: 200px" class="underline-input" />
        </div>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="4">
        <div class="input-with-label">
          <label class="input-label">ASN数量</label>
          <el-input v-model="asnQuantity" style="width: 200px" class="underline-input" />
        </div>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="4" style="align-items: center">
        <div class="input-with-label">
          <label class="input-label">SN总数: </label>
          <el-input v-model="snQuantity" style="width: 120px" disabled class="prominent-display" />
        </div>
      </el-col>
      <el-col :span="3" style="align-items: center">
        <div class="input-with-label">
          <label class="input-label">已选中箱数: </label>
          <el-input v-model="boxQuantity" style="width: 80px" disabled class="prominent-display" />
        </div>
      </el-col>
      <el-col :span="2">
        <div class="mb-4" style="margin-left: 25px">
          <el-button type="primary" @click="getBox">查询</el-button>
        </div>
      </el-col>
      <el-col :span="2" style="margin-left: 25px">
        <div class="mb-4">
          <el-button type="primary" @click="submitUpload">上传</el-button>
        </div>
      </el-col>
      <el-col :span="2">
        <div class="mb-4">
          <el-button type="primary" @click="showSidebar">结果显示</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row style="margin-top: 8px">
      <el-table
        ref="tableRef"
        :data="storeDataList"
        border
        height="68vh"
        @selection-change="handleSelectionChange"
        :row-key="getRowKey"
        @select="handleSelect"
        @select-all="handleSelectAll">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column prop="superprocessgroupname" label="外箱号" align="center" />
        <el-table-column prop="mpnId" label="客户料号" align="center" />
        <el-table-column prop="mpn" label="供应商料号" align="center" />
        <el-table-column prop="materialquantity" label="箱内数量" align="center" />
      </el-table>
    </el-row>
    <el-row class="pagination-container">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="page"
        :page-sizes="[100, 200, 500]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" />
    </el-row>

    <el-drawer v-model="drawer" title="上传信息" :with-header="true">
      <template #header="{ titleId, titleClass }">
        <div v-loading="exportLoading">
          <el-row>
            <h4 :id="titleId" :class="titleClass">上传信息</h4>
            <el-button type="warning" plain icon="download" @click="handleExportButton()">导出</el-button>
          </el-row>
          <el-row>
            {{ drawerMessage }}
          </el-row>
        </div>
      </template>
    </el-drawer>
  </div>
</template>


<script setup name="sendasn">
import { getOuterBoxInfo, Upload } from '@/api/product/sendasn'
import { Fgcodelist } from '@/api/infoSerch/wipSerch'
import * as XLSX from 'xlsx'
import _, { get } from 'lodash'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
//侧边栏控制开关
const drawer = ref(false)
//侧边栏信息
const drawerMessage = ref('')
//页面加载状态
const fullscreenLoading = ref(false)
//侧边栏加载状态
const exportLoading = ref(false)
//关联表格
const tableRef = ref()
//单选框，选择使用环境
const radioEl = ref('product')
//单选框，选择使用客户，先默认为维信诺
const radioClient = ref('BOE')
//选择框，FGCODE
const FgcodeOptions = ref([])
//输入框，boxid
const boxId = ref('')
//获取FGCODE
const productSpecName = ref('')
//asn号
const asnNo = ref('')
//asn数量
const asnQuantity = ref('')
//sn总数
const snQuantity = ref(0)
//箱数
const boxQuantity = ref(0)
//数据分页
const total = ref(0)
const pageSize = ref(100)
const page = ref(1)

const state = reactive({
  storeDataList: [], //存当前页数据
  storeDataListAll: [], //所有页数据
  retInfo: {},
  retMessage: '',
  selectedRows: [], //勾选行
  selectedBoxes: new Set() // 存储所有选中的外箱号
})

const { storeDataList, storeDataListAll, selectedRows, selectedBoxes } = toRefs(state)

// 获取行的唯一标识
function getRowKey(row) {
  return row.superprocessgroupname
}

// 查询fgcode
function getFgcodeList() {
  Fgcodelist().then((res) => {
    if (radioClient.value == 'BOE') {
      FgcodeOptions.value = [{ productSpecName: 'ZC-A1D32B-028_V03' }]
    } else {
      FgcodeOptions.value = res.data
    }
  })
}
getFgcodeList()

//根据FGCODE获得信息
function getBox() {
  // 进入加载页面
  fullscreenLoading.value = true
  //清空表格数据和选中状态
  storeDataListAll.value = []
  storeDataList.value = []
  selectedRows.value = []
  selectedBoxes.value.clear()
  snQuantity.value = 0
  boxQuantity.value = 0

  //产品型号，箱号同时为空时，不执行
  if ((productSpecName.value == '' || productSpecName.value == null) && (boxId.value.trim() == '' || boxId.value == null)) {
    ElMessage.error('请输入产品型号或箱号')
    //退出加载页面
    fullscreenLoading.value = false
    return
  }
  //获取箱号
  getOuterBoxInfo({ productSpecName: productSpecName.value, cartonStr: boxId.value.trim() }).then((res) => {
    total.value = res.data.length
    storeDataListAll.value = res.data
    getTableData()
    //离开加载页面
    fullscreenLoading.value = false
  })
}

// 获得选中行的数据
// const getDataSubmit = () => {
//   console.log(selectedRows.value)
// }

//上传选中的selection中的信息
function submitUpload() {
  // 判断radioClient是否为空
  if (radioClient.value == '') {
    ElMessage.error('请选择要上传的客户')
    return
  }

  //判断选中的数据是否为空
  if (selectedRows.value.length == 0) {
    ElMessage.error('请选择要上传的箱号')
    return
  }

  //判断asn是否为空
  if (asnNo.value.trim() == '' || asnNo.value == null) {
    ElMessage.error('填写要上传的ASN')
    return
  }

  //判断asn数量是否为空
  if (asnQuantity.value.trim() == '' || asnQuantity.value == null) {
    ElMessage.error('填写要上传的ASN数量')
    return
  }

  //判断asn数量和sn总数是否一致
  if (asnQuantity.value.trim() != snQuantity.value.toString()) {
    ElMessage.error('ASN数量和SN总数不一致')
    return
  }

  //进入加载界面
  fullscreenLoading.value = true

  //获得选中行的外包号
  let tempboxid = selectedRows.value
    .map((item) => (item.superprocessgroupname ? item.superprocessgroupname.toString() : ''))
    .filter((item) => item !== '')

  Upload({
    asnNo: asnNo.value.trim(),
    asnQuantity: asnQuantity.value.trim(),
    cartons: tempboxid,
    environment: radioEl.value,
    client: radioClient.value,
    productSpecName: productSpecName.value,
    CartonQuantity: selectedRows.value
  })
    .then((res) => {
      drawer.value = true
      drawerMessage.value = res.data
      if (res.data.header.code === 200) {
        ElMessage.success(boxQuantity.value + '箱上传成功' + res.data.header.desc)
        getBox()
      } else if (res.data.header.code === 5001) {
        //退出加载界面
        fullscreenLoading.value = false
        ElMessage.warning(boxQuantity.value + '箱上传成功,本地数据库更新失败')
      } else {
        //退出加载界面
        fullscreenLoading.value = false
      }
    })
    .finally(() => {
      //退出加载界面
      fullscreenLoading.value = false
    })
}

function sizeChange(val) {
  pageSize.value = val
  page.value = 1
  getTableData()
}

function getTableData() {
  storeDataList.value = storeDataListAll.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value)

  // 恢复选中状态
  setTimeout(() => {
    restoreSelection()
  }, 50)
}

function currentChange(val) {
  page.value = val
  getTableData()
}

// 恢复选中状态
function restoreSelection() {
  if (!tableRef.value) return

  // 清除当前所有选中
  tableRef.value.clearSelection()

  // 遍历当前页数据，选中之前已选中的行
  storeDataList.value.forEach((row) => {
    if (selectedBoxes.value.has(row.superprocessgroupname)) {
      tableRef.value.toggleRowSelection(row, true)
    }
  })
}

// 处理单个选择
function handleSelect(selection, row) {
  if (selection.includes(row)) {
    // 选中
    if (!selectedBoxes.value.has(row.superprocessgroupname)) {
      selectedBoxes.value.add(row.superprocessgroupname)
      selectedRows.value.push(row)
      snQuantity.value += parseInt(row.materialquantity || 0)
      boxQuantity.value += 1
    }
  } else {
    // 取消选中
    if (selectedBoxes.value.has(row.superprocessgroupname)) {
      selectedBoxes.value.delete(row.superprocessgroupname)
      selectedRows.value = selectedRows.value.filter((item) => item.superprocessgroupname !== row.superprocessgroupname)
      snQuantity.value -= parseInt(row.materialquantity || 0)
      boxQuantity.value -= 1
    }
  }
}

// 处理全选
function handleSelectAll(selection) {
  if (selection.length === 0) {
    // 取消全选
    storeDataList.value.forEach((row) => {
      if (selectedBoxes.value.has(row.superprocessgroupname)) {
        selectedBoxes.value.delete(row.superprocessgroupname)
        selectedRows.value = selectedRows.value.filter((item) => item.superprocessgroupname !== row.superprocessgroupname)
        snQuantity.value -= parseInt(row.materialquantity || 0)
        boxQuantity.value -= 1
      }
    })
  } else {
    // 全选
    storeDataList.value.forEach((row) => {
      if (!selectedBoxes.value.has(row.superprocessgroupname)) {
        selectedBoxes.value.add(row.superprocessgroupname)
        selectedRows.value.push(row)
        snQuantity.value += parseInt(row.materialquantity || 0)
        boxQuantity.value += 1
      }
    })
  }
}

function handleExportButton() {
  if (drawerMessage.value.body.carton) {
    exportToExcel(drawerMessage.value.body.carton, '箱号')
  }
  if (drawerMessage.value.body.sn) {
    exportToExcel(drawerMessage.value.body.sn, 'SN')
  }
  if (drawerMessage.value.body.other) {
    exportToExcel(drawerMessage.value.body.other, '错误信息')
  }
}

// 快速导出所有数据到excel表格，仅前端一个方法
function exportToExcel(xlsxlist, fileNamePrefix) {
  exportLoading.value = true
  const data = xlsxlist
  // exportLoading.value = true
  // if (data.length === 0) {
  //   drawer.value = true // 数据为空，显示抽屉并设置消息
  //   drawerMessage.value = '嗨，没有数据可以导出'
  //   exportLoading.value = false
  // } else {
  //   exportLoading.value = false
  // }
  const now = new Date()
  const fileNameSuffix = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now
    .getDate()
    .toString()
    .padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now
    .getSeconds()
    .toString()
    .padStart(2, '0')}`
  // const fileName = `${fileNamePrefix}_${fileNameSuffix}.xlsx`
  const fileName = `${fileNamePrefix}${fileNameSuffix}.xlsx`
  const headers = Object.keys(data[0]).map((key) => ({
    header: key, // 将字段名作为标题
    key: key // key与字段名相同
  }))
  // headers.forEach((headerObj) => {
  //   const customHeaders = {
  //     superprocessgroupname: '外箱号',
  //     processgroupname: '内箱号',
  //     lotno: '批次号',
  //     ocid: '屏体码',
  //     moduleid: '制程码',
  //     customerid: '客户码',
  //     modelsn: '注胶码',
  //     productrequestname: '华麟工单',
  //     productspecname: '型号',
  //     lasteventtime: '最后事件时间',
  //     lasteventuser: '最后事件人'
  //   }
  //   if (customHeaders[headerObj.key]) {
  //     headerObj.header = customHeaders[headerObj.key]
  //   }
  // })
  const sheetData = [headers.map((h) => h.header)] // 第一行是标题
  sheetData.push(...data.map((item) => headers.map((h) => item[h.key])))
  const worksheet = XLSX.utils.aoa_to_sheet(sheetData)

  //const worksheet = XLSX.utils.json_to_sheet(data)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
  exportLoading.value = false
}

// 显示侧边栏
function showSidebar() {
  drawer.value = true
}

//监听FGCODE下拉列表
watch(productSpecName, () => {
  getBox()
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: right;
}

.underline-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: none;
  border-bottom: 1px solid #dcdfe6;
  border-radius: 0;
  padding-left: 0;
  padding-right: 0;
}

.underline-input :deep(.el-input__wrapper.is-focus) {
  border-bottom: 1px solid var(--el-color-primary);
}

.underline-input :deep(.el-input__inner::placeholder) {
  color: #c0c4cc;
  font-size: 14px;
}

.input-with-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
}

.prominent-display :deep(.el-input__inner) {
  font-size: 16px;
  font-weight: bold;
  color: #1a1a1a;
  text-align: center;
  background-color: #f0f9eb; /* 浅绿色背景，更醒目 */
}

.prominent-display :deep(.el-input__wrapper) {
  background-color: #f0f9eb;
}
</style>
